import { app, BrowserWindow, dialog, ipcMain, Menu, protocol, shell } from "electron"
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import path from "path"
import url from 'url'
import DBUtils from './db'
import { createProtocol } from "vue-cli-plugin-electron-builder/lib"
import Downloader from 'nodejs-file-downloader'
import fs from 'fs'
import os from 'os'

export default class ElectronApp {
	mainWindow:BrowserWindow | undefined
	expressServer:any

	public async whenReady(){
		electronApp.setAppUserModelId('com.electron')
	
		app.on('browser-window-created', (_, window) => {
			optimizer.watchWindowShortcuts(window)
		})

		app.on('activate',  ()=> {
			if(this.mainWindow){
				this.mainWindow.show()
			}
		})
		

		protocol.registerFileProtocol('local', (request, callback) => {
			const filePath = url.fileURLToPath('file://' + request.url.slice('local://'.length))
			callback(filePath)
		})
	}

	public createWindow(){
		const config=require('../../../package.json')

		this.mainWindow = new BrowserWindow({
			title:"Electron Demo v"+config.version,
			width: 960,
			height: 720,
			minWidth:960,
			minHeight:720,
			show: false,
			autoHideMenuBar: true,
			useContentSize:true,
			...(process.platform === 'linux'
				? {
					icon: path.join(__dirname, '../../build/icon.png')
				}
				: {}),
			webPreferences: {
				preload: path.join(__dirname, './preload.js'),
				sandbox: false,
				webSecurity:false,
				devTools: is.dev,
				nodeIntegration: false,
				contextIsolation: true
			}
		})
		this.mainWindow.on('page-title-updated', (evt) => {
			evt.preventDefault();
		});
		if(is.dev){
			this.mainWindow!.webContents.openDevTools();
		}
		this.mainWindow.on('ready-to-show', async () => {
			this.mainWindow!.show()
		})
		this.mainWindow.on('close', async (e) => {
			e.preventDefault()
			this.mainWindow.hide()
		})
		this.mainWindow.webContents.setWindowOpenHandler((details) => {
			shell.openExternal(details.url)
			return { action: 'deny' }
		})

		if (is.dev && process.env.WEBPACK_DEV_SERVER_URL) {
			this.mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string)
		} else {
			createProtocol('app')
			this.mainWindow.loadURL('app://./index.html')
		}
		
	}

	
	public registerHandle(){
		ipcMain.handle('main:openFile', this.openFileHandle)
		ipcMain.handle('main:openNewWindow', (e,data)=>this.openNewWindow(data))
		ipcMain.handle('main:openUrl', (e,data)=>this.openUrl(data))
	}

	private openNewWindow(data){
		var newWindow = new BrowserWindow({
			...data,
			// parent:this.mainWindow,
			useContentSize:true,
			webPreferences: {
				preload: path.join(__dirname, './preload.js'),
				sandbox: false,
				webSecurity:false,
				devTools: is.dev,
				nodeIntegration: false,
				contextIsolation: true
			}
		})
		if(is.dev){
			newWindow.webContents.openDevTools();
		}
		newWindow.on('page-title-updated', (evt) => {
			evt.preventDefault();
		});
		if (is.dev && process.env.WEBPACK_DEV_SERVER_URL) {
			newWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL+'#'+data.path)
		} else {
			newWindow.loadURL('app://./index.html/#'+data.path)
		}
	}

	private async openFileHandle(){
		const window = BrowserWindow.getFocusedWindow();
		const { canceled, filePaths } = await dialog.showOpenDialog(window!,{
			title:"选择文件",
			properties: ['openFile']
		})
		if (canceled) {
			return
		} else {
			return filePaths[0]
		}
	}

	private openUrl(url){
		shell.openExternal(url)
	}

	public async destroyed(){
		
	}
}